#!/usr/bin/env python3
"""
诊断视频拆分问题
"""
import asyncio
import subprocess
from pathlib import Path
from app.services.video_splitter import VideoSplitter
from app.utils.logger import logger

async def diagnose_video_split():
    """诊断视频拆分问题"""
    print("🔍 诊断视频拆分问题...")
    
    # 1. 检查FFmpeg
    print("\n1️⃣ 检查FFmpeg安装...")
    try:
        result = subprocess.run(['ffmpeg', '-version'], 
                              capture_output=True, text=True, timeout=10)
        if result.returncode == 0:
            version_line = result.stdout.split('\n')[0]
            print(f"✅ FFmpeg已安装: {version_line}")
        else:
            print(f"❌ FFmpeg检查失败: {result.stderr}")
            return False
    except FileNotFoundError:
        print("❌ FFmpeg未找到，请安装FFmpeg")
        return False
    except Exception as e:
        print(f"❌ FFmpeg检查异常: {e}")
        return False
    
    # 2. 检查测试视频
    print("\n2️⃣ 检查测试视频...")
    uploads_dir = Path("uploads")
    video_files = list(uploads_dir.glob("*.mp4"))
    
    if not video_files:
        print("❌ 没有找到测试视频文件")
        return False
    
    test_video = video_files[0]
    print(f"📹 使用测试视频: {test_video.name}")
    print(f"   文件大小: {test_video.stat().st_size / (1024*1024):.1f}MB")
    
    # 3. 检查视频信息
    print("\n3️⃣ 获取视频信息...")
    splitter = VideoSplitter()
    try:
        video_info = await splitter._get_video_info(test_video)
        print(f"✅ 视频信息获取成功:")
        print(f"   时长: {video_info.get('duration', 0):.1f}秒")
        print(f"   分辨率: {video_info.get('width', 0)}x{video_info.get('height', 0)}")
        print(f"   帧率: {video_info.get('fps', 0):.1f}fps")
    except Exception as e:
        print(f"❌ 获取视频信息失败: {e}")
        return False
    
    # 4. 测试简单的FFmpeg切分
    print("\n4️⃣ 测试FFmpeg切分...")
    try:
        # 创建测试输出目录
        test_dir = Path("uploads/test_segments")
        test_dir.mkdir(exist_ok=True)
        
        # 测试切分前10秒
        test_output = test_dir / "test_segment.mp4"
        
        cmd = [
            "ffmpeg",
            "-i", str(test_video),
            "-ss", "0",
            "-t", "10",
            "-c", "copy",
            "-avoid_negative_ts", "make_zero",
            "-y",
            str(test_output)
        ]
        
        print(f"   执行命令: {' '.join(cmd)}")
        
        process = await asyncio.create_subprocess_exec(
            *cmd,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE
        )
        
        stdout, stderr = await process.communicate()
        
        if process.returncode == 0 and test_output.exists():
            file_size = test_output.stat().st_size
            print(f"✅ FFmpeg切分测试成功: {file_size} bytes")
            
            # 清理测试文件
            test_output.unlink()
            test_dir.rmdir()
        else:
            stderr_text = stderr.decode('utf-8', errors='ignore')
            print(f"❌ FFmpeg切分测试失败:")
            print(f"   返回码: {process.returncode}")
            print(f"   错误信息: {stderr_text[:500]}...")
            return False
            
    except Exception as e:
        print(f"❌ FFmpeg切分测试异常: {e}")
        return False
    
    # 5. 测试完整的视频拆分流程
    print("\n5️⃣ 测试完整拆分流程...")
    try:
        result = await splitter.split_video_by_duration(
            test_video,
            segment_duration=30,  # 30秒一段
            max_segments=3,       # 最多3段
            min_segment_duration=5
        )
        
        print(f"✅ 拆分流程完成:")
        print(f"   需要拆分: {result.get('need_split', False)}")
        print(f"   片段数量: {len(result.get('segments', []))}")
        
        if result.get('segments'):
            for i, segment in enumerate(result['segments'][:2]):  # 只显示前2个
                print(f"   片段{i+1}: {segment['filename']} ({segment['duration']:.1f}s)")
        
        return len(result.get('segments', [])) > 0
        
    except Exception as e:
        print(f"❌ 完整拆分流程失败: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == "__main__":
    success = asyncio.run(diagnose_video_split())
    if success:
        print("\n🎉 诊断完成，视频拆分功能正常！")
    else:
        print("\n❌ 发现问题，需要修复视频拆分功能。")
        print("\n💡 可能的解决方案:")
        print("   1. 安装FFmpeg: https://ffmpeg.org/download.html")
        print("   2. 检查视频文件是否损坏")
        print("   3. 检查文件权限")
        print("   4. 查看详细错误日志")